package com.nit.generate;

import com.nit.tools.loop.NitLoopTools;

import java.util.Random;

/**
 * @ClassName NitMacGenerator
 * @Description MAC地址生成器
 * @Author by
 * @Date 21/7/2023 上午9:48
 * @Version 1.0
 */
public class NitMacGenerator {

    public static void main(String[] args) {
        NitLoopTools.loop(4, () -> {
            String tmp = NitMacGenerator.generate();
            System.out.println("随机mac地址:" + tmp + "<br>");
        });
    }

    public static String generate() {
        Random random = new Random();
        byte[] macAddressBytes = new byte[6];
        random.nextBytes(macAddressBytes);

        // 将第一个字节的第二位最低有效位设置为0(单播地址)
        macAddressBytes[0] = (byte) (macAddressBytes[0] & (byte) 254);

        StringBuilder macAddressBuilder = new StringBuilder();
        for (int i = 0; i < macAddressBytes.length; i++) {
            macAddressBuilder.append(String.format("%02X", macAddressBytes[i]));
            if (i < macAddressBytes.length - 1) {
                macAddressBuilder.append(":");
            }
        }

        return macAddressBuilder.toString();
    }
}
